package com.sdkj.fixed.asset.system.controller;



import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageHelper;
import com.sdkj.fixed.asset.api.system.UserApi;
import com.sdkj.fixed.asset.api.system.in_vo.UserBindRole;
import com.sdkj.fixed.asset.api.system.in_vo.UserConditionEntity;
import com.sdkj.fixed.asset.api.system.in_vo.UserDataAuth;
import com.sdkj.fixed.asset.api.system.in_vo.UserEditPassword;
import com.sdkj.fixed.asset.common.base.*;
import com.sdkj.fixed.asset.common.core.RoleType;
import com.sdkj.fixed.asset.common.exception.LogicException;
import com.sdkj.fixed.asset.common.utils.FileDownload;
import com.sdkj.fixed.asset.pojo.system.OrgManagement;
import com.sdkj.fixed.asset.pojo.system.UserManagement;
import com.sdkj.fixed.asset.pojo.system.group.*;
import com.sdkj.fixed.asset.system.service.OrgService;
import com.sdkj.fixed.asset.system.service.UserService;
import com.sdkj.fixed.asset.system.util.CacheUtil;
import com.sdkj.fixed.asset.system.util.ExcelUtils;
import com.sdkj.fixed.asset.system.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName UserController
 * @Description 用户管理控制层
 * @Author 张欣
 * @Date 2020/7/21 9:24
 */
@Controller
public class UserController extends BaseController<UserManagement> implements UserApi {

    @Autowired
    private UserService userService;
    @Autowired
    private OrgService orgService;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private CacheUtil cacheUtil;
    @Autowired
    private RedisUtil redisUtil;
    @Override
    public BaseService getService() {
        return userService;
    }
    /**
     * 新增用户
     * @param userManagement
     * @return
     * @throws Exception
     */
    @Override
    public BaseResultVo insertSimple(@RequestBody @Validated(addUser.class) UserManagement userManagement) throws Exception{
        String token = request.getHeader("token");
        String userId = cacheUtil.getUserId(token);
        userManagement.setCuser(userId);
        userManagement.setEuser(userId);
        if(cacheUtil.getUserRole(token).contains(RoleType.SYSADMIN.getRoleType())){
            userManagement.setTopCompanyId(userManagement.getCompanyId());
        }else{
            userManagement.setTopCompanyId(cacheUtil.getUserCompanyId(token));
        }
        boolean isLock = false;
        while (!isLock){
            isLock = redisUtil.setnx("USER_EMPLOYEE",5000);
            if(isLock){
                try {
                     userService.addUser(userManagement);
                     redisUtil.del("USER_EMPLOYEE");
                } catch (Exception e){
                    redisUtil.del("USER_EMPLOYEE");
                    throw e;
                }
                continue;
            }else{
                Thread.sleep(5000);
            }

        }
        return BaseResultVo.success("",userManagement.getId());
    }
    /**
     * 修改用户
     * @param userManagement
     * @return
     * @throws Exception
     */
    @Override
    public BaseResultVo updateById(@RequestBody @Validated(UserEdit.class) UserManagement userManagement) throws Exception{
        String token = request.getHeader("token");
        String userId = cacheUtil.getUserId(token);
        userManagement.setEuser(userId);
        userService.editUser(userManagement);
        return BaseResultVo.success("",userManagement.getId());
    }
    /**
     * 设置或取消管理员
     * @param userManagement
     * @return
     * @throws Exception
     */
    @Override
    public BaseResultVo setUserAdmin(@Validated(SetUserAdmin.class) UserManagement userManagement) throws Exception{
        String token = request.getHeader("token");
        String userId = cacheUtil.getUserId(token);
        userManagement.setEuser(userId);

        userService.setUserAdmin(userManagement,token);
        return BaseResultVo.success("",userManagement.getId());
    }
    /**
     * 禁用或启用员工
     * @param userManagement
     * @return
     */
    @Override
    public BaseResultVo forbiddenOrEnable(@Validated(ForbiddenOrEnableUser.class) UserManagement userManagement) throws Exception{
        String token = request.getHeader("token");
        String userId = cacheUtil.getUserId(token);
        userManagement.setEuser(userId);
        userService.forbiddenOrEnable(userManagement);
        return BaseResultVo.success("",userManagement.getId());
    }

    /**
     * 删除员工
     * @param userManagement
     * @return
     * @throws Exception
     */
    @Override
    public BaseResultVo deleteOrRecoverUser(@Validated(ForbiddenOrEnableUser.class) UserManagement userManagement) throws Exception{
        String token = request.getHeader("token");
        String userId = cacheUtil.getUserId(token);
        userManagement.setEuser(userId);
        userService.deleteUser(userManagement);
        return BaseResultVo.success("",userManagement.getId());
    }
    /**
     * 查询已绑定的角色
     * @param userManagement
     * @return
     */
    @Override
    public BaseResultVo queryHasRole(@Validated(IdMustUser.class) UserManagement userManagement) throws Exception{
        return BaseResultVo.success(userService.queryHasBindRole(userManagement.getId()));
    }
    /**
     * 绑定角色
     * @param userBindRole
     * @return
     */
    @Override
    public BaseResultVo bindRole(@Validated UserBindRole userBindRole) throws Exception{
        userService.userBlindRole(userBindRole);
        return BaseResultVo.success();
    }
    /**
     * 数据权限
     * @param userDataAuth
     * @return
     */
    @Override
    public BaseResultVo bindDataAuth(@Validated UserDataAuth userDataAuth) throws Exception{
        String token = request.getHeader("token");
        String userId = cacheUtil.getUserId(token);
        userService.bindDataAuth(userDataAuth,userId);
        return BaseResultVo.success();
    }
    /**
     * 查看已绑定的数据权限
     * @param userManagement
     * @return
     */
    @Override
    public BaseResultVo queryHasDataAuth(@Validated(IdMustUser.class) UserManagement userManagement) throws Exception{
        return BaseResultVo.success(userService.queryHasDataAuth(userManagement.getId()));
    }
    /**
     * 修改密码
     * @param userEditPassword
     * @return
     */
    @Override
    public BaseResultVo editPassword(@Validated UserEditPassword userEditPassword) throws Exception{
        String token = request.getHeader("token");
        String userId = cacheUtil.getUserId(token);
        userService.editPassword(userEditPassword,userId);
        return BaseResultVo.success();
    }
    /**
     * 获取员工详情
     * @param userManagement
     * @return
     */
    @Override
    public BaseResultVo queryUserInfo(@Validated(IdMustUser.class) UserManagement userManagement) throws Exception{
        UserManagement resultVo = userService.selectByPrimaryKey(userManagement.getId());
        if(resultVo == null){
            throw new LogicException("用户不存在");
        }
        OrgManagement userManagement1 = orgService.selectByPrimaryKey(resultVo.getCompanyId());
        resultVo.setCompanyName(userManagement1.getName());
        resultVo.setCompanyTreeCode(userManagement1.getTreecode().replace(resultVo.getCompanyId()+",","").replace(resultVo.getCompanyId(),""));
        OrgManagement userManagement2 = orgService.selectByPrimaryKey(resultVo.getDeptId());
        String treecode = userManagement2.getTreecode();
        String[] treecodes = treecode.split(",");
        for(String str : treecodes){
            OrgManagement orgManagement = orgService.selectByPrimaryKey(str);
            if(orgManagement.getType() == 1){
                treecode.replace(orgManagement.getId()+",","");
            }
        }
        resultVo.setDeptName(userManagement2.getName());
        resultVo.setDeptTreeCode(treecode);
        return BaseResultVo.success(resultVo);
    }
    /**
     * 查询总公司下所有启用的系统用户
     *
     * @return
     */
    @Override
    public BaseResultVo queryAllEnableUser(String companyId) throws Exception {

        String token = request.getHeader("token");
        if(cacheUtil.getUserRole(token).contains(RoleType.SYSADMIN.getRoleType()) && StrUtil.isBlank(companyId)){
            throw new LogicException("公司不能为空");
        }
        if(!cacheUtil.getUserRole(token).contains(RoleType.SYSADMIN.getRoleType())){
            companyId = cacheUtil.getUserCompanyId(token);
        }
        List<UserManagement> userManagements = userService.queryAllEnableUser(companyId);
        return BaseResultVo.success(userManagements);
    }
    /**
     * 分页查询用户
     *
     * @return
     */
    @Override
    public BaseResultVo getPageUser(@RequestBody PageParams<UserConditionEntity> params){
        PageHelper.startPage(params.getCurrentPage(), params.getPerPageTotal());
        List<UserManagement> pageUser = userService.getPageUser(params);
        PageBean<UserManagement> page = new PageBean<UserManagement>( pageUser);
        return BaseResultVo.success(page);

    }

    /**
     * 下载用户模板
     * @param response
     * @throws Exception
     */
    @Override
    public void downUserTemp(HttpServletResponse response) throws Exception{
        FileDownload.fileDownload(response,request,getClass().getResource("/").getPath()+"/template/员工批量导入模板.xlsx","员工批量导入模板.xlsx");
    }

    /**
     * 导入用户
     * @param file
     * @return
     * @throws Exception
     */
    @Override
    public BaseResultVo importUser(MultipartFile file)  throws Exception{
        String token = request.getHeader("token");
        if(cacheUtil.getUserRole(token).contains(RoleType.SYSADMIN.getRoleType())){
            throw new LogicException("超级管理员不能导入用户");
        }
        if(file == null){
            throw  new LogicException("文件不能为空");
        }
        if(!file.getOriginalFilename().endsWith(".xlsx")){
            throw  new LogicException("文件类型必须为【.xlsx】");
        }
        if(file.getSize() > 10*1024*1024){
            throw  new LogicException("文件最大允许10MB");
        }


        userService.importUser(file,cacheUtil.getUserCompanyId(token),cacheUtil.getUserId(token));
        return BaseResultVo.success();
    }

    /**
     * 导出用户
     * @param companyId
     * @param response
     * @throws Exception
     */
    @Override
    public void exportUser(String companyId,HttpServletResponse response)  throws Exception{
        List<UserManagement> list =  userService.getAllUser(companyId);
        String fileName = "系统用户";
        ExcelUtils.exportExcel(list,UserManagement.class,fileName,response);

    }
    /**
     *查询所有资产启用状态分类
     */
    @Override
    public BaseResultVo getAllEnableAssetClass()  throws Exception{
        String token = request.getHeader("token");
        List<String> roleLevel = cacheUtil.getUserRole(token);
        if(roleLevel.contains(RoleType.SYSADMIN.getRoleType())){
            return BaseResultVo.success(new ArrayList<>());
        }
        String userCompanyId = cacheUtil.getUserCompanyId(token);
        return BaseResultVo.success(userService.getAllEnAbleAssetClass(userCompanyId));
    }
    /**
     *查询所有启用状态的区域分类
     */
    @Override
    public BaseResultVo getAllEnableArea()  throws Exception{
        String token = request.getHeader("token");
        List<String> roleLevel = cacheUtil.getUserRole(token);
        if(roleLevel.contains(RoleType.SYSADMIN.getRoleType())){
            return BaseResultVo.success(new ArrayList<>());
        }
        String userCompanyId = cacheUtil.getUserCompanyId(token);
        return BaseResultVo.success(userService.getAllEnAbleArea(userCompanyId));
    }
}
